package chaw.android.train;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.HttpRequestManager;
import chaw.android.util.ImageSave;
import chaw.android.util.ImageTurn;
import chaw.android.util.ImageUpload;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;

public class BoardWriteActivity extends Activity {
	protected static final int CALLER_REQUEST = 0;
	private EditText eTitle, eContent;
	private ImageButton addpic, btn1, btn2, btn3, btn4, btn5;
	private ImageView cancel, back, facebook;
	private String title, content, meet = "0", lodge = "0", restaurant = "0", place = "0", etc = "0";
	private String img1 = "", img2 = "", img3 = "", img4 = "", main_img = "";
	private String user_id, station_id, station_name;
	private boolean check = false, upload = false;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
        setContentView(R.layout.board_write);
        
        addpic = (ImageButton) findViewById(R.id.add_picture);
        btn1 = (ImageButton) findViewById(R.id.btn1);
        btn2 = (ImageButton) findViewById(R.id.btn2);
        btn3 = (ImageButton) findViewById(R.id.btn3);
        btn4 = (ImageButton) findViewById(R.id.btn4);
        btn5 = (ImageButton) findViewById(R.id.btn5);
        cancel = (ImageView) findViewById(R.id.cancel);
        back = (ImageView) findViewById(R.id.back);
        facebook = (ImageView) findViewById(R.id.facebook);

		facebook.setImageResource(R.drawable.btn_fb_off);

		if(!Preferences.getValue(getBaseContext(), "access_token").toString().equals("null") && !Preferences.getValue(getBaseContext(), "access_token").toString().equals("")){
			
			check = true;
		}
		if(!Preferences.getValue(getBaseContext(), "facebook").toString().equals("null") && !Preferences.getValue(getBaseContext(), "facebook").toString().equals("")){
			if(Preferences.getValue(getBaseContext(), "facebook").toString().equals("true")){
				upload = true;
				facebook.setImageResource(R.drawable.btn_fb_on);
			}
		}
        new Handler().postDelayed(new Runnable(){
        	@Override
        	public void run() {
        		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        		imm.showSoftInput(findViewById(R.id.title), 0);  
        	}
        }, 100);
        setClickListener();
	}

	public void setClickListener(){

		facebook.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.v("d",Preferences.getValue(getBaseContext(), "access_token"));
				if(!check){
					startActivityForResult(new Intent(getBaseContext(), FacebookActivity.class), 1);					
				}
				else{
					if(upload){
						upload = false;
						facebook.setImageResource(R.drawable.btn_fb_off);
						Preferences.setValue(getBaseContext(), "facebook", "false");
					}
					else{
						upload = true;
						facebook.setImageResource(R.drawable.btn_fb_on);
						Preferences.setValue(getBaseContext(), "facebook", "true");
					}
				}
			}
		});

		back.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				eTitle = (EditText)findViewById(R.id.title);
				eContent = (EditText)findViewById(R.id.content);
				title = eTitle.getText().toString();
				content = eContent.getText().toString();
				user_id = Preferences.getValue(getBaseContext(), "user_id");
				Intent intent = getIntent();
				station_id = intent.getExtras().get("station_id").toString();
				station_name = intent.getExtras().get("station_name").toString();
				UploadAsynkTask task = new UploadAsynkTask();
				String[] params = new String[]{};

				if(title.length() > 0 && content.length() > 0){
					if(meet.equals("0") && lodge.equals("0") && restaurant.equals("0") && place.equals("0") && etc.equals("0")){
						etc = "1";
					}
					task.execute(params);	
				}
				else{
					Toast.makeText(getBaseContext(), "제목/내용은 최소 한 글자 이상이여야 합니다.", Toast.LENGTH_SHORT).show();
				}
			}
		});
		cancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		addpic.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getBaseContext(), BoardPictureActivity.class);
				startActivityForResult(intent, CALLER_REQUEST);
			}
		});
		btn1.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(meet.equals("0")){
					meet = "1";
					btn1.setImageResource(R.drawable.btn_theme_meet_on);
				}
				else{
					meet = "0";
					btn1.setImageResource(R.drawable.btn_theme_meet_off);	
				}
			}
		});
		btn2.setOnClickListener(new View.OnClickListener() {	
		
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(lodge.equals("0")){
					lodge = "1";
					btn2.setImageResource(R.drawable.btn_theme_lodge_on);
				}
				else{
					lodge = "0";
					btn2.setImageResource(R.drawable.btn_theme_lodge_off);	
				}
			}
		});
		btn3.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(restaurant.equals("0")){
					restaurant = "1";
					btn3.setImageResource(R.drawable.btn_theme_food_on);
				}
				else{
					restaurant = "0";
					btn3.setImageResource(R.drawable.btn_theme_food_off);	
				}
			}
		});
		btn4.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(place.equals("0")){
					place = "1";
					btn4.setImageResource(R.drawable.btn_theme_tour_on);
				}
				else{
					place = "0";
					btn4.setImageResource(R.drawable.btn_theme_tour_off);	
				}
			}
		});
		btn5.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(etc.equals("0")){
					etc = "1";
					btn5.setImageResource(R.drawable.btn_theme_etc_on);
				}
				else{
					etc = "0";
					btn5.setImageResource(R.drawable.btn_theme_etc_off);	
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent){
		if(requestCode == CALLER_REQUEST && resultCode == RESULT_OK){
			ArrayList<String> imagelist = intent.getExtras().getStringArrayList("image");
			img1 = imagelist.get(0);
			img2 = imagelist.get(1);
			img3 = imagelist.get(2);
			img4 = imagelist.get(3);
			main_img = intent.getExtras().get("main").toString();
			if(main_img != ""){
	   	        String filePath = checkMain(main_img);
	   			Bitmap image = BitmapFactory.decodeFile(filePath);
				int degree = ImageTurn.getExifOrientation(filePath);
				image = ImageTurn.getResourceBitmap(image, degree);
				addpic.setImageBitmap(image);
				addpic.setScaleType(ScaleType.FIT_XY);
				addpic.setBackgroundResource(R.drawable.btn_camera_mark);
			}
		}
		if(requestCode == 1){
			check = true;
			upload = true;
			facebook.setImageResource(R.drawable.btn_fb_on);
			//facebook access결과 확인
		}
	}
	public String checkMain(String main){
		if(main.equals("1")){
			return img1;
		}
		else if(main.equals("2")){
			return img2;
		}
		else if(main.equals("3")){
			return img3;
		}
		else if(main.equals("4")){
			return img4;
		}
		else{
			return "";
		}
	}

	private class UploadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub

			ImageUpload upload = new ImageUpload(ServerURL.addBoardDev);
			upload.addData("title", title);
			upload.addData("content", content);
			upload.addData("user_id", user_id);
			upload.addData("meet", meet);
			upload.addData("lodge", lodge);
			upload.addData("restaurant", restaurant);
			upload.addData("place", place);
			upload.addData("etc", etc);
			upload.addData("image_main", main_img);
			upload.addData("station_id", station_id);
			
			String message = Preferences.getValue(getBaseContext(), "nick_name") + "님이 " + station_name + "에 새 글을 올렸습니다.";
			upload.addData("message", message.toString());
			
			SimpleDateFormat formatter = new SimpleDateFormat ( "yyyyMMddHHmmss", Locale.KOREA );
			Date currentTime = new Date ( );
			String dTime = formatter.format ( currentTime );
			String rTime = "" + (int)(Math.random() * 1000 ) % 1000;
			String imageUrl = dTime + "_" + rTime + "_";
			if(!img1.equals("")){
				upload.upItem(new File(img1), "image1", user_id , "image_1", imageUrl);
				
				Bitmap thumbImage = BitmapFactory.decodeFile(img1);
				thumbImage = Bitmap.createScaledBitmap(thumbImage, 160, 160, false);
				OutputStream output;
				try {
					File tempFile = new File(ImageSave.getImageDir() + "/tempThumbFile.jpg");
					output = new FileOutputStream(tempFile);
					thumbImage.compress(Bitmap.CompressFormat.JPEG, 100, output);
					upload.upItem(tempFile, "image1_thumb", user_id , "image_1_thumb", imageUrl);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(!img2.equals("")){
				upload.upItem(new File(img2), "image2", user_id, "image_2", imageUrl);
				
				Bitmap thumbImage = BitmapFactory.decodeFile(img2);
				thumbImage = Bitmap.createScaledBitmap(thumbImage, 160, 160, false);
				OutputStream output;
				try {
					File tempFile = new File(ImageSave.getImageDir() + "/tempThumbFile.jpg");
					output = new FileOutputStream(tempFile);
					thumbImage.compress(Bitmap.CompressFormat.JPEG, 100, output);
					upload.upItem(tempFile, "image2_thumb", user_id , "image_2_thumb", imageUrl);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(!img3.equals("")){
				upload.upItem(new File(img3), "image3", user_id, "image_3", imageUrl);
				
				Bitmap thumbImage = BitmapFactory.decodeFile(img3);
				thumbImage = Bitmap.createScaledBitmap(thumbImage, 160, 160, false);
				OutputStream output;
				try {
					File tempFile = new File(ImageSave.getImageDir() + "/tempThumbFile.jpg");
					output = new FileOutputStream(tempFile);
					thumbImage.compress(Bitmap.CompressFormat.JPEG, 100, output);
					upload.upItem(tempFile, "image3_thumb", user_id , "image_3_thumb", imageUrl);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(!img4.equals("")){
				upload.upItem(new File(img4), "image4", user_id, "image_4", imageUrl);
				
				Bitmap thumbImage = BitmapFactory.decodeFile(img4);
				thumbImage = Bitmap.createScaledBitmap(thumbImage, 160, 160, false);
				OutputStream output;
				try {
					File tempFile = new File(ImageSave.getImageDir() + "/tempThumbFile.jpg");
					output = new FileOutputStream(tempFile);
					thumbImage.compress(Bitmap.CompressFormat.JPEG, 100, output);
					upload.upItem(tempFile, "image4_thumb", user_id , "image_4_thumb", imageUrl);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			String result = upload.getResponse();
	        Log.d("BoardWrite", result);
	        JSONObject response;
	        String board_id = "";
			try {
				response = new JSONObject(result);
				board_id = response.get("board_id").toString();
				return board_id;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "fail";
			}
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Log.v("d",result);
			if(result.equals("fail")){
				
			}
			else{
				if(upload){
					UploadAsynkTask2 task = new UploadAsynkTask2();
					task.execute(new String[]{ServerURL.facebook_upload, "board_id", result, "access_token", Preferences.getValue(getBaseContext(), "access_token")});
				}	
			}
		}
	}

	private class UploadAsynkTask2 extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try{
				JSONObject returnValue = new JSONObject(result);
				if(returnValue.has("id")){
					Log.v("v", "Success to write feed on Facebook");
					finish();
				}
				else{
					Intent intent = new Intent(getBaseContext(), FacebookActivity.class);
					startActivity(intent);
				}
			}catch (Exception e) {
				// TODO: handle exception
			}
			Log.v("task2",result);
		}
	}

}
